/**
 * 
 */
package xj.toolkit.ebus.actors;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xj.toolkit.ebus.EventBus;
import xj.toolkit.util.ClosureEx;


/**
 * @author hp
 *
 */
public class MultiEventActor extends AbstractEventActor {

    private static final Logger logger = 
    	LoggerFactory.getLogger(MultiEventActor.class);
    
    private List<Runnable>	dtors = 
    	new ArrayList<Runnable>();
    
    private	Map<String, ClosureEx>	closures = 
    	new HashMap<String, ClosureEx>();
    
	public Map<String, ClosureEx> getClosures() {
		return Collections.unmodifiableMap( closures );
	}

	public Map<String, String> getEventMapping() {
    	Map<String, String>	ret = new HashMap<String, String>();
        for (Map.Entry<String, ClosureEx> entry : this.closures.entrySet()) {
        	ret.put(entry.getKey(), entry.getValue().toString());
        }
        
        return	ret;
	}
	
	public void setClosures(Map<String, ClosureEx> closures) {
        this.closures.clear();
        
        for (Map.Entry<String, ClosureEx> entry : closures.entrySet()) {
            if ( null != entry.getValue() ) {
                this.closures.put(entry.getKey(), entry.getValue());
            }
        }
	}

	public MultiEventActor(EventBus ebus, String name) {
        super(ebus, name);
    }

	public void start() {
        for (Map.Entry<String, ClosureEx> entry : this.closures.entrySet()) {
        	String event = entry.getKey();
        	dtors.add( registerObserver( event, entry.getValue() ) );
        }
	}
	
    public void destroy() {
    	for ( Runnable canceler : dtors ) {
	        try {
	        	canceler.run();
	        } catch (Exception e) {
	        	logger.error("destroy:", e);
	        }
    	}
    	dtors.clear();
        
        super.destroy();
    }

}
